package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.service.impl.IEmployeeServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeServiceImpl service;

    //后台系统登录
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee one = service.getOne(qw);
        if (one == null) {
            return R.error("查询不到，登录失败!");
        }
        if (one.getPassword().equals(password)) {

            if (one.getStatus() == 0) {
                return R.error("用户已被禁用!");
            }
            one.setPassword(null);
            session.setAttribute("employee", one.getId());
            return R.success(one);
        }
        return R.error("登录失败");

/*        //3、如果没有查询到则返回登录失败结果
        if(one == null){
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!one.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        session.setAttribute("employee",one.getId());
        return R.success(one);
    }*/
    }

    /**
     * 员工退出
     *
     * @param
     * @return
     */
    //员工退出
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        //清理Session中保存的当前登录员工的id
        session.removeAttribute("employee");
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //0、检查数据，哪些是需要处理的
        //0.1: 密码使用默认的123456 ， 需要加密 DigestUtils.md5DigestAsHex
        // 0.2： status 不需要处理，数据库默认是1
        // 0.3： create_time 和 update_time ,设置为当前系统时间  LocalDateTime.now()
        // 0.4： create_user 和 update_user 创建人和修改人，应该是当前登陆人，从session中获取

        // 1、调用业务层保存 employee数据

        // 2、返回结果R

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
    /*    employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/
        service.save(employee);
        return R.success(employee.getUsername() + "添加成功");
    }

    //员工分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Employee> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        qw.orderByDesc(Employee::getUpdateTime);
        service.page(page1, qw);
        return R.success(page1);

    }

    //员工的启用和禁用
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpServletRequest request) {
/*        employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);*/
        service.updateById(employee);
        return R.success("员工信息修改成功");
    }

    //编辑员工
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = service.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) {

        try {
            response.setHeader("Content-Disposition",
                "attachment; filename=employee.xlsx");
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream("D:\\img\\abc.xlsx");
            List<Employee> list = service.list();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            EasyExcel.write("D:\\img\\abc.xlsx", Employee.class).sheet("模板").doWrite(list);

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
